package cn.swust.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import cn.swust.model.InformationBean;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class StaticFreemarker {
	/** 
     * 初始化模板引擎 
     *  
     * @param ftl 模板名称 
     * @param htmlName 需要生成html页面的名称 
     * @param map 模板中需要的参数集合 
     * @param relativePath 模板相对于根路径的相对路径 
     * @throws IOException 
     * @throws TemplateException 
     */  
    @SuppressWarnings("unchecked")  
    public void init(String ftl, String htmlName, List<InformationBean> list, String relativePath)  
            throws IOException, TemplateException {  
         
    	Configuration cfg = new Configuration();
    	//模版文件的位置，relativePath为相对工程的路径
        cfg.setServletContextForTemplateLoading(ServletActionContext  
        		.getServletContext(), "/" + relativePath);  
        cfg.setEncoding(Locale.getDefault(), "utf-8");  
         //根据模版位置获得模版 
        Template template = cfg.getTemplate(ftl);  
        template.setEncoding("utf-8");  
          
        String path = ServletActionContext.getServletContext().getRealPath("/");          
        File htmlFile = new File(path + htmlName);  
        Writer out = new BufferedWriter(new OutputStreamWriter(  
                new FileOutputStream(htmlFile), "utf-8"));  
        //处理合并
        template.process(list, out); 
        out.flush();  
        out.close();  
    }  
  
}
